﻿using LiveChartsCore;
using LiveChartsCore.SkiaSharpView;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Serilog;
using Serilog.Events;
using Serilog.Sinks.Debug;
using Serilog.Sinks.File;
using SkiaSharp;
using StudentInfoSystem.Core.Models;
using StudentInfoSystem.UI.Services;
using StudentInfoSystem.UI.ViewModels;
using StudentInfoSystem.UI.Views;
using StudentInfoSystem.UI.Views.Pages;
using StudentInfoSystem.UI.Views.Windows;
using System.Configuration;
using System.Data;
using System.IO;
using System.Windows;

namespace StudentInfoSystem.UI;

/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
    private StartupTaskManager? _taskManager;

    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);
        // 创建启动窗口
        var splashScreen = new SplashScreenWindow();
        splashScreen.Show();

        // 配置 Serilog
        var loggerConfig = new LoggerConfiguration()
            .MinimumLevel.Debug()
            .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
            .Enrich.FromLogContext();

        // 只在调试模式下添加Debug和Console输出
#if DEBUG
        loggerConfig.WriteTo.Debug();
#endif

        // 始终添加文件输出（适用于所有配置）
        loggerConfig.WriteTo.File(
                path: Path.Combine("Logs", "log-.txt"),
                rollingInterval: RollingInterval.Day,
                retainedFileCountLimit: 30,
                outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}");

        Log.Logger = loggerConfig.CreateLogger();

        // 创建任务管理器
        _taskManager = new StartupTaskManager(
            splashScreen,
            InitializeMainWindow,
            () => {
                // 启动后执行的操作
                ThemeService.ApplyTheme(AppSettings.Instance.IsDarkTheme);

                // 立即关闭启动窗口
                splashScreen.Close();
                // 增强的自动登录检查
                if (AppSettings.Instance.IsAutoLogin && AppSettings.Instance.CurrentUser != null)
                {
                        // 设置当前用户
                        ShowMainWindowImmediately();
                }
                else if (AppSettings.Instance.IsAutoLogin &&
                         AppSettings.Instance.CurrentUser == null)
                {
                    // 自动登录启用但没有记住的账户，显示警告
                    MessageBox.Show("自动登录已启用但未找到保存的账户信息，请重新登录",
                                   "自动登录失败", MessageBoxButton.OK, MessageBoxImage.Warning);
                    ShowLoginWindowDuringStartup();
                }
                else
                {
                    ShowLoginWindowDuringStartup();
                }
            }
        );

        // 在后台线程启动加载
        Task.Run( () => _taskManager.StartAsync());
    }

    protected override void OnExit(ExitEventArgs e)
    {
        _taskManager?.Stop();
        Log.CloseAndFlush(); // 确保所有日志都被写入
        base.OnExit(e);
    }

    // 主窗口初始化方法
    private void InitializeMainWindow()
    {
        // 配置LiveCharts 全局设置字体
        LiveCharts.Configure(config => config.HasGlobalSKTypeface(SKFontManager.Default.MatchCharacter('汉')));

        // 使用BeginInvoke避免阻塞UI线程
        Dispatcher.BeginInvoke(() =>
        {
            var mainWindow = new MainWindow();
            Application.Current.MainWindow = mainWindow;

            // 预加载但不显示，减少首次显示的延迟
            mainWindow.Visibility = Visibility.Hidden;

            Log.Information("主窗口初始化完成");
        });
    }

    private void ShowMainWindowImmediately()
    {
        Dispatcher.Invoke(() =>
        {
            if (Application.Current.MainWindow != null)
            {
                Application.Current.MainWindow.Show();
                Application.Current.MainWindow.Activate();
                Application.Current.MainWindow.Focus();
            }
        });
    }

    private void ShowLoginWindowDuringStartup()
    {
        Dispatcher.Invoke(() =>
        {
            var loginWindow = new LoginWindow { IsDuringStartup = true };
            bool loginSuccess = false; // 添加局部变量记录登录是否成功
            loginWindow.LoginSuccess += (user) =>
            {
                loginSuccess = true; // 标记登录成功
                loginWindow.Close();
                ShowMainWindowImmediately();
            };
            loginWindow.Closed += (s, e) =>
            {
                // 只有在非登录成功关闭、没有记住账户且是启动过程时才退出应用
                if (!loginSuccess && AppSettings.Instance.CurrentUser == null && loginWindow.IsDuringStartup)
                {
                    Application.Current.Shutdown();
                }
            };
            loginWindow.ShowDialog();
        });
    }
}
